package cn.ren.service;

import cn.ren.dao.MenuDao;
import cn.ren.dao.PermissionDao;
import cn.ren.dao.RoleDao;
import cn.ren.dao.UserDao;
import cn.ren.entity.PageResult;
import cn.ren.entity.QueryPageBean;
import cn.ren.entity.Result;
import cn.ren.pojo.*;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: itcast_health
 * @description:
 * @author: ren
 * @create: 2020-03-03 10:51
 **/
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;

    @Override
    public User findUserByName(String username) {
        //根据userDao查询user
        User user = userDao.findUserByName(username);
        if (user == null){
            return null;
        }
        //根据userid查询拥有的角色role，
        Set<Role> roleSet = roleDao.findRoleByUserId(user.getId());
        //根据roleid查询所有的权限，并保存到role中
        if (roleSet != null && roleSet.size() > 0){
            for (Role role : roleSet) {
                Set<Permission> permissionSet = permissionDao.findByRoleId(role.getId());
                if (permissionSet != null && permissionSet.size() > 0){
                    role.setPermissions(permissionSet);
                }
            }
        }
        //保存role到user中
        user.setRoles(roleSet);
        return user;
    }

    @Override
    public List<Map<String, Object>> findMenuByUsername(String username) {
        //通过用户名查询所有的菜单列表
        List<Menu> menu = getMenuList(username);
        System.out.println(menu);
        List<Map<String, Object>> result = null;
        if (menu != null && menu.size() > 0){
            //从第一级菜单开始，通过递归将列表以层级关系保存到list
            result = getResultByRecursion(menu, 0);
        }
        return result;
    }

    @Override
    public PageResult lzFindPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = userDao.lzFindPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public Result lzAdd(User user, int... checkgroupIds) {

        try {
            userDao.lzAdd(user);
            Integer id = user.getId();
            if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (int checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("userid",id);
                map.put("roleid",checkgroupId);
                userDao.lzAddUserRole(map);
            }}
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"添加失败");
        }

        return new Result(true,"添加成功");
    }

    /**
     * 根据用户名获取其所有的菜单项
     * @param username
     * @return
     */
    public List<Menu> getMenuList(String username){
        User user = userDao.findUserByName(username);
        if (user != null){
            Set<Role> roleSet = roleDao.findRoleByUserId(user.getId());
            //根据角色id去获取所有的菜单项
            List<Menu> menu = new ArrayList<>();
            for (Role role : roleSet) {
                List<Menu> menuSet = menuDao.findMenuByRoleId(role.getId());
                //遍历该角色下的菜单set，将结果保存在menu中
                for (Menu menu1 : menuSet) {
                    menu.add(menu1);
                }
            }
            //防止拥有多个角色，出现菜单重复，对list去重
            List<Menu> collect = menu.stream().distinct().collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    public List<Map<String,Object>> getResultByRecursion(List<Menu> set,int i){
        List<Map<String,Object>> list = new ArrayList<>();
        //遍历set，查询是否有ParentMenuId是i的对象
        for (Menu menu : set) {
            Integer parentMenuId = menu.getParentMenuId();
            if(parentMenuId==null){
                parentMenuId=0;
            }
            if (parentMenuId == i){
                //将该menu对象数据封装到Map，加入list中
                Map<String,Object> map = new HashMap<>();
                map.put("path",menu.getPath());
                map.put("title",menu.getName());
                map.put("icon",menu.getIcon());
                map.put("linkUrl",menu.getLinkUrl());
                //根据该级菜单的id，递归查询下一级菜单
                List<Map<String, Object>> childrenList = getResultByRecursion(set, menu.getId());
                map.put("children",childrenList);
                //将该map保存到list里
                list.add(map);
            }
        }
        return list;
    }
}